package org.micode.libs.smon.utils;

import org.micode.libs.smon.vo.DiskInfo;
import oshi.SystemInfo;
import oshi.software.os.FileSystem;
import oshi.software.os.OSFileStore;
import oshi.software.os.OperatingSystem;

import java.util.ArrayList;
import java.util.List;

public class DiskUtils {

    private final static SystemInfo systemInfo = new SystemInfo();

    private final static OperatingSystem operatingSystem = systemInfo.getOperatingSystem();


    public static List<DiskInfo> readDiskList() {
        List<DiskInfo> list = new ArrayList<>();
        fillDisks(list);
        return list;
    }

    public static void fillDisks(List<DiskInfo> list) {
        if (null == list) {
            return;
        }

        list.clear();

        FileSystem fileSystem = operatingSystem.getFileSystem();
        List<OSFileStore> fsList = fileSystem.getFileStores();
        for (OSFileStore fs : fsList) {

//            System.out.println(fs.getName() + " 磁盘名称\n" +
//                    fs.getVolume() + " 文件集\n" +
//                    fs.getLogicalVolume() + " 合理的文件集\n" +
//                    fs.getMount() + " 盘符\n" +
//                    fs.getDescription() + " 描述\n" +
//                    fs.getType() + " 类型");

            DiskInfo disk = new DiskInfo();

            disk.setDiskName(fs.getMount());
            disk.setDiskType(fs.getDescription());
            disk.setFileType(fs.getType());

            disk.setTotalSpace(fs.getTotalSpace());
            disk.setFreeSpace(fs.getFreeSpace());
            disk.setUsableSpace(fs.getUsableSpace());
            disk.setUsedSpace(disk.getTotalSpace() - disk.getUsableSpace());

            if (disk.getTotalSpace() > 0) {
                disk.setSpaceUsage(disk.getUsedSpace() / (1.0 * disk.getTotalSpace()));
            } else {
                disk.setSpaceUsage(0);
            }
            list.add(disk);
        }
    }

    public static void main(String[] args) {
        List<DiskInfo> list = readDiskList();
        list.forEach(item -> {
            System.out.println("名称: " + item.getDiskName() +
                    ", 类型: " + item.getDiskType() +
                    ", 文件系统: " + item.getFileType() +
                    ", 总量: " + item.getTotalSpace() +
                    ", 剩余量: " + item.getFreeSpace() +
                    ", 可用量: " + item.getUsableSpace() +
                    ", 使用量: " + item.getUsedSpace() +
                    ", 使用率: " + item.getSpaceUsage());
        });
    }

}
